<template>
  <ContentContainer :pagination="pagination" :loading="loading" @run="run">
    <template #header-prefix>
      <a-alert
        v-if="nodeDetails?.cascade_level === 2"
        type="warning"
        class="mb-6"
        >当前节点层级为 L2，安全配置不生效。</a-alert
      >
      <a-radio-group
        v-model="moduleType"
        type="button"
        @change="handleModuleChange">
        <a-radio :value="3">白名单</a-radio>
        <a-radio :value="1">自定义规则</a-radio>
        <a-radio :value="2">速率规则</a-radio>
      </a-radio-group>
    </template>
    <template #header>
      <a-button type="primary" @click="openDeploy">
        <i-icons-btn-add />
        部署规则</a-button
      >
      <CloudFilterBar
        v-model="queryParams"
        :run="run"
        :schemes="filterScheme"></CloudFilterBar>
    </template>
    <a-table
      ref="tableRef"
      v-bind="commonTableProps"
      :columns="columns"
      :data="data">
      <template #strategy="{ record }">
        <div class="flex items-center gap-x-6px">
          <i-icons-observe v-if="record.action === 3" />
          <i-icons-prevent v-if="record.action === 1" />
          <i-icons-js v-if="record.action === 4" />
          <i-icons-inquiry v-if="record.action === 5" />
          <span>{{ getOptionsLabel(wafCustomOptions, record.action) }}</span>
        </div>
      </template>

      <template #action="{ record }">
        <a-link :hoverable="false" @click="openDrawer(record)">详情</a-link>
        <a-link :hoverable="false" status="danger" @click="handleDelete(record)"
          >移除</a-link
        >
      </template>
    </a-table>
    <RuleDetails
      v-model="visible"
      :type="moduleType"
      :rule-id="detailData?.id ?? ''" />
    <DeployRules
      v-model:visible="deployVisible"
      :type="moduleType"
      @refresh="run" />
  </ContentContainer>
</template>
<script lang="ts" setup>
import type { NodeDetails } from '@/apis/model/node'
import type { WafListItem } from '@/apis/model/waf'
import { getApiNodeApi } from '@/apis/modules/node/node'
import { deleteWafNodeUnbindApi, getApiWafQueryApi } from '@/apis/modules/waf'
import type { CloudFilterBarWidget } from '@/components/filter-bar/types'
import { wafStrategyOptions, wafCustomOptions } from '@/constants'
import { getOptionsLabel } from '@/utils'
import { commonTableProps, type BuildTabColumnsData } from '@/utils/table'
import RuleDetails from './components/RuleDetails.vue'
import DeployRules from './components/DeployRules.vue'
import { useConfigStore } from '@/stores/config'
const route = useRoute()

const queryParams = ref<any>({
  scope: 3,
  order: 'asc',
  sort: 'priority'
})

const moduleType = ref(3)
const { visible: deployVisible, open: openDeploy } = usePopup()
const { visible, open: openDrawer, data: detailData } = usePopup<WafListItem>()
const nodeDetails = ref<NodeDetails>()

const columns = computed(() => {
  const rule: BuildTabColumnsData = {
    title: '执行策略',
    slotName: 'strategy'
  }

  const jumpModule: BuildTabColumnsData = {
    title: '跳过模块',
    dataIndex: 'jump',
    render({ record }) {
      const list = record.module_config.skip_module ?? []
      return list
        .map((item: number) => getOptionsLabel(skipModuleOptions, item))
        .join(', ')
    }
  }
  const commonColumns: BuildTabColumnsData[] = [
    {
      title: '规则 ID',
      dataIndex: 'id',
      format: 'copy'
    },
    {
      title: '规则名称',
      dataIndex: 'name',
      format: 'copy'
    },
    {
      title: '描述',
      dataIndex: 'condition_description'
    },

    {
      title: '状态',
      render({ record }) {
        return record.status === 1 ? '开启' : '关闭'
      }
    },
    {
      title: '操作',
      slotName: 'action',
      width: 112,
      cellClass: 'actions-cell'
    }
  ]
  if (moduleType.value === 3) {
    commonColumns.splice(3, 0, jumpModule)
  } else {
    commonColumns.splice(2, 0, rule)
  }

  return buildColumns(commonColumns)
})
const filterScheme = computed(() => {
  const customTem: CloudFilterBarWidget = {
    widget: 'select',
    field: 'action',
    allText: '全部执行策略',
    placeholder: '请选择执行策略',
    options: wafCustomOptions
  }

  const tem: CloudFilterBarWidget = {
    widget: 'select',
    field: 'action',
    allText: '全部执行策略',
    placeholder: '请选择执行策略',
    options: wafStrategyOptions
  }

  const commonWidget: CloudFilterBarWidget = {
    widget: 'strong-search',
    placeholder: '默认按照规则 ID 搜索',
    options: [
      {
        maxLength: 19,
        label: '规则 ID',
        messageModel: 'message',
        message: '规则 ID 格式不正确',
        validate: validateRuleID,
        field: 'id'
      },
      {
        label: '规则名称',
        field: 'name_keyword',
        maxLength: 30
      }
    ]
  }
  if (moduleType.value === 3) {
    return {
      widgets: [commonWidget]
    }
  } else if (moduleType.value === 1) {
    return {
      widgets: [customTem, commonWidget]
    }
  } else if (moduleType.value === 2) {
    return {
      widgets: [tem, commonWidget]
    }
  }
})

const { data, loading, run, pagination } = useListRequest(getApiWafQueryApi, {
  params: queryParams,
  immediate: false
})
const handleModuleChange = (v: number | string | boolean) => {
  queryParams.value = {
    ...queryParams.value,
    module: v as number
  }

  queryParams.value.action = 0
  useConfigStore().getCondition({ module: v })
  run()
}
const handleDelete = (row: any) => {
  CloudModal.error(
    {
      content: `确认从节点移除规则 “${row?.name}” ？`,
      okText: '移除'
    },
    async () => {
      await deleteWafNodeUnbindApi({
        id: route.params.id as string,
        module: moduleType.value,
        waf_ids: [row?.id]
      })
      ToastUtils.success('操作成功')
      run!()
    }
  )
}
const getNodeInfo = () => {
  // 获取节点信息
  getApiNodeApi({ id: queryParams.value.bind_id }).then((res) => {
    nodeDetails.value = res
  })
}

watch(
  () => route.params.id,
  (v) => {
    if (v) {
      queryParams.value.bind_id = v as string
      queryParams.value.module = moduleType.value
      getNodeInfo()
      run()
    }
  },
  {
    immediate: true
  }
)
</script>
